﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// <see cref="HttpRequestHeaders"/> 扩展操作类
    /// </summary>
    public static class HttpRequestHeadersExtensions
    {
        /// <summary>
        /// 设置HttpClient的Headers值，如存在，则先移除
        /// </summary>
        /// <param name="headers"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void Set(this HttpRequestHeaders headers, string name, string value)
        {
            if (headers.Contains(name))
            {
                headers.Remove(name);
            }
            try
            {
                headers.Add(name, value);
            }
            catch (FormatException)
            {
                headers.TryAddWithoutValidation(name, value);
            }
        }

    }

    /// <summary>
    /// <see cref="HttpResponseHeaders"/> 扩展操作类
    /// </summary>
    public static class HttpResponseHeadersExtensions
    {   
        /// <summary>
        /// 尝试从 <see cref="HttpResponseHeaders"/> 中提取 Cookie 值
        /// </summary>
        /// <param name="headers"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool TryGetCookie(this HttpResponseHeaders headers, string name, out string value)
        {
            value = string.Empty;
            bool flag = headers.TryGetValues("Set-Cookie", out IEnumerable<string> cookies);
            if (!flag)
            {
                return false;
            }
            value = cookies.Where(m => m.Contains($"{name}=")).Select(m => m.Substring($"{name}=", ";", "")).FirstOrDefault();
            return !value.IsNullOrEmpty();
        }

        /// <summary>
        /// 尝试从 <see cref="HttpResponseHeaders"/> 中提取 Refresh 的 URL
        /// </summary>
        /// <param name="headers"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool TryGetRefreshUrl(this HttpResponseHeaders headers, out string url)
        {
            url = null;
            if (!headers.TryGetValues("Refresh", out IEnumerable<string> values))
            {
                return false;
            }
            url = values.First().Substring("url=", "");
            return true;
        }


    }

}
